package com.solcoo.task;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.solcoo.dao.RecommendDao;
import com.solcoo.dao.UseromrelaDao;
import com.solcoo.dao.YongHuDao;
import com.solcoo.dao.ZhangHuDao;
import com.solcoo.pojo.Recommend;
import com.solcoo.pojo.Useromrela;
import com.solcoo.pojo.YongHu;
import com.solcoo.util.JJCZUtil;
import com.solcoo.util.SendMsgUtil;

@Component
public class RewardTask {

	private static Logger logger = Logger.getLogger(RewardTask.class);
	
	@Resource
	private RecommendDao recommendDao;
	@Resource
	private YongHuDao yongHuDao;
	@Resource
	private ZhangHuDao zhangHuDao;
	@Resource
	private UseromrelaDao useromrelaDao;
	
	@Scheduled(cron = "0 0 7 * * ?")
	public void charge() {
		try {
			logger.error("RewardTask~~~~~start~~~~~~~~~~~~~~~~~~~~");
			Map<String, Date> czjlsjs = new HashMap<String, Date>(); // KEY:个人手机号；VALUE:最近推荐时间
			Map<String, String> czjls = new HashMap<String, String>(); // KEY:个人手机号；VALUE:充值手机号,推荐ID
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			String today = formatter.format(new Date());
			List<Recommend> rs = recommendDao.getRewardRecommend(today);
			if(rs!=null && rs.size()>0) {
				// 里面各种校验，顺序注意，调整顺序会带来bug
				for(Recommend r:rs) {
					String czjl = "";
					// 推荐个人才有效
					if(!"2".equals(r.getApptype())) {
						recommendDao.updateRewardRecommend(r.getId().intValue());
						logger.error("RewardTask---------type is not invalid:id=" + r.getId());
						continue;
					}

					// 个人注册时间晚于推荐时间有效
					String gerentele = r.getTelephone();
					YongHu geren = yongHuDao.selectUserByPhone(gerentele);
					if(geren==null) {
						continue;
					}
					if(geren.getZhucesj().compareTo(r.getCreateTime())<=0) {
						recommendDao.updateRewardRecommend(r.getId().intValue());
						logger.error("RewardTask---------time1 is not invalid:id=" + r.getId());
						continue;
					}

					// 获取推荐人
					String recommended = r.getRecommended();
					YongHu recommendYh = yongHuDao.selectUserByYonghum(recommended);
					czjl = recommendYh.getShoujih(); // 充值的手机号
					
					// 商户、子账户推荐则校验是否有效商户
					if("1".equals(r.getRdtype())) {
						if(!"1".equals(recommendYh.getEnabled())) {
							recommendDao.updateRewardRecommend(r.getId().intValue());
							logger.error("RewardTask---------recommended1 is not invalid:id=" + r.getId());
							continue;
						}
					} else if("3".equals(r.getRdtype())) {
						Useromrela ur = useromrelaDao.getEnabledEmployee(recommended);
						if(ur != null) {
							recommended = ur.getOwnerid();
							recommendYh = yongHuDao.selectUserByYonghum(recommended);
							if(!"1".equals(recommendYh.getEnabled())) {
								recommendDao.updateRewardRecommend(r.getId().intValue());
								logger.error("RewardTask---------recommended2 is not invalid:id=" + r.getId());
								continue;
							}
						} else {
							recommendDao.updateRewardRecommend(r.getId().intValue());
							logger.error("RewardTask---------recommended3 is not invalid:id=" + r.getId());
							continue;
						}
					}

					// 距离个人注册时间最近的为有效推荐
					if(czjlsjs.get(gerentele) == null) {
						czjlsjs.put(gerentele, r.getCreateTime());
					} else {
						if(r.getCreateTime().compareTo(czjlsjs.get(gerentele)) > 0) {
							String sxjl = czjls.get(gerentele);
							if(sxjl!=null && !"".equals(sxjl)) {
								recommendDao.updateRewardRecommend(Integer.parseInt(sxjl.split(",")[1]));
								czjls.remove(gerentele);
							} else {
								logger.error("RewardTask~~~~~kao!has logic bug!");
							}
						} else {
							recommendDao.updateRewardRecommend(r.getId().intValue());
							logger.error("RewardTask---------time2 is not invalid:id=" + r.getId() + "; valid is " + czjls.get(gerentele));
							continue;
						}
					}
					
					// 必须在有效商户上充值，商户、子账户推荐则必须改该店首次充值且充值金额至少50
					Integer shida = zhangHuDao.queryShidA(Integer.parseInt(geren.getYonghum()));
					if(shida==null || shida<=0) {
						logger.error("RewardTask---------chongzhi is not invalid:id=" + r.getId());
						continue;
					}
					
					if("1".equals(r.getRdtype()) || "3".equals(r.getRdtype())) {
						if(shida!=null && !shida.equals(Integer.parseInt(recommended))) {
							recommendDao.updateRewardRecommend(r.getId().intValue());
							logger.error("RewardTask---------merchant is not invalid:id=" + r.getId());
							continue;
						}
					}

					// 增加有效充值记录
					czjl += "," + r.getId();
					czjls.put(r.getTelephone(), czjl);
				}
				
				if(czjls.size() > 0) {
//					String content = "";
					for(String key:czjls.keySet()) {
						String czjl = czjls.get(key);
						String mobile = czjl.split(",")[0];
						String out_trade_id = czjl.split(",")[1];
						String result = new JJCZUtil().jjcz(mobile, "10", out_trade_id);
						
//						if(result!=null && result.indexOf("<return><result>0</result>")>0) {
//							logger.error("RewardTask result: id==" + out_trade_id + "; mobile==" + mobile);
//							recommendDao.updateRewardRecommend(Integer.parseInt(czjl.split(",")[1]));
//						} else {
							logger.error("RewardTask result: id==" + out_trade_id + "; result==" + result);
//						}
						
//						content += czjl.split(",")[0] + ";";
					}
//					if(!"".equals(content)) {
//						content += "【充值测试】";
//						logger.error("RewardTask---------content==" + content);
//						new SendMsgUtil("15381031851", content, "2").SendMsg();
//					}
				}
			}
			logger.error("RewardTask~~~~~end~~~~~~~~~~~~~~~~~~~~");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
}